package in.hbb20.countrycodepickerproject.fragment;

import com.hbb20.CountryCodePicker;
import com.hbb20.FocusLine;
import in.hbb20.countrycodepickerproject.ResourceTable;
import com.hbb20.utils.Toast;
import ohos.agp.components.*;
import ohos.app.Context;

public class CountryPreferenceFragment extends Fragment {
    private TextField editTextCountryPreference;
    private Button buttonSetCountryPreference;
    private CountryCodePicker ccp;
    private Button buttonNext;

    public CountryPreferenceFragment(Context context) {
        super(context);
    }

    @Override
    protected Component onCreateView(LayoutScatter layoutScatter, ComponentContainer container) {
        return layoutScatter.parse(ResourceTable.Layout_fragment_country_preference, null, false);
    }

    @Override
    protected void onViewCreate() {
        assignViews();
        editTextWatcher();
        addClickListeners();
    }

    private void assignViews() {
        ScrollView scrollview = (ScrollView) findComponentById(ResourceTable.Id_scrollview);
        editTextCountryPreference = (TextField) findComponentById(ResourceTable.Id_editText_countryPreference);
        FocusLine.drawFocusLine(editTextCountryPreference, findComponentById(ResourceTable.Id_component_line), scrollview);

        ccp = (CountryCodePicker) findComponentById(ResourceTable.Id_ccp);
        buttonSetCountryPreference = (Button) findComponentById(ResourceTable.Id_button_setCountryPreference);
        buttonNext = (Button) findComponentById(ResourceTable.Id_button_next);
        Text textDf1 = (Text) findComponentById(ResourceTable.Id_text_def1);
        String text = "<com.hbb20.CountryCodePicker \n ohos:id=\"$+id:ccp\" \n ohos:width=\"match_content\" \n ohos:height=\"match_content\" \n app:ccp_defaultNameCode=\"US\" \n app:ccp_countryPreference=\"US,IN,NZ\"/>;";
        textDf1.setText(text);
    }

    private void addClickListeners() {

        buttonSetCountryPreference.setClickedListener(component -> {
            String countryPreference = editTextCountryPreference.getText();
            ccp.setCountryPreference(countryPreference);
            Toast.showShort(mContext, "Country preference list has been changed, click on CCP to see them at top of list.");
        });

        buttonNext.setClickedListener(component -> {
            if (mChangeFragment != null) {
                mChangeFragment.changeFragment(mChangeFragment.getCurrentPage() + 1);
            }
        });
    }

    private void editTextWatcher() {

        editTextCountryPreference.addTextObserver((s, i, i1, i2) -> {
            String text = "set +" + s + " as Country preference.";
            buttonSetCountryPreference.setText(text);
        });
    }
}
